import { _decorator, AudioClip, AudioSource, game } from "cc";
import { Singleton } from "../decorators/Singleton";
const { ccclass } = _decorator;

@Singleton
@ccclass("AudioManager")
export class AudioManager {
  private _audioMap: Map<string, AudioClip> = new Map();
  private _bgmVolume: number = 1.0;
  private _sfxVolume: number = 1.0;
  private _currentBGM: AudioSource = null;

  constructor() {
    // 从本地存储加载音量设置
    const bgmVolume = localStorage.getItem("bgmVolume");
    const sfxVolume = localStorage.getItem("sfxVolume");
    if (bgmVolume) this._bgmVolume = parseFloat(bgmVolume);
    if (sfxVolume) this._sfxVolume = parseFloat(sfxVolume);

    // 游戏隐藏时暂停背景音乐
    game.on(game.EVENT_HIDE, () => {
      if (this._currentBGM) {
        this._currentBGM.pause();
      }
    });

    // 游戏显示时恢复背景音乐
    game.on(game.EVENT_SHOW, () => {
      if (this._currentBGM) {
        this._currentBGM.play();
      }
    });
  }

  public async playBGM(clip: AudioClip, loop: boolean = true): Promise<void> {
    if (this._currentBGM) {
      this._currentBGM.stop();
    }

    const audioSource = new AudioSource();
    audioSource.clip = clip;
    audioSource.loop = loop;
    audioSource.volume = this._bgmVolume;
    audioSource.play();

    this._currentBGM = audioSource;
  }

  public async playSFX(clip: AudioClip): Promise<void> {
    const audioSource = new AudioSource();
    audioSource.clip = clip;
    audioSource.loop = false;
    audioSource.volume = this._sfxVolume;
    audioSource.play();

    // 播放完成后自动清理
    audioSource.node.once(AudioSource.EventType.ENDED, () => {
      audioSource.destroy();
    });
  }

  public setBGMVolume(volume: number): void {
    this._bgmVolume = Math.max(0, Math.min(1, volume));
    if (this._currentBGM) {
      this._currentBGM.volume = this._bgmVolume;
    }
    localStorage.setItem("bgmVolume", this._bgmVolume.toString());
  }

  public setSFXVolume(volume: number): void {
    this._sfxVolume = Math.max(0, Math.min(1, volume));
    localStorage.setItem("sfxVolume", this._sfxVolume.toString());
  }

  public stopBGM(): void {
    if (this._currentBGM) {
      this._currentBGM.stop();
      this._currentBGM = null;
    }
  }

  public pauseBGM(): void {
    if (this._currentBGM) {
      this._currentBGM.pause();
    }
  }

  public resumeBGM(): void {
    if (this._currentBGM) {
      this._currentBGM.play();
    }
  }
}
